<template>
  <div class="container" id="login-container">
    <div class="login">
      <div class="login-text">系统登录</div>
      <el-form
        :model="form"
        ref="formValidate"
        :rules="rules"
        label-width="0"
        :inline="false"
      >
        <el-form-item prop="username">
          <el-input
            v-model="form.username"
            @keyup.enter="handleLogin"
            placeholder="账号"
          >
            <template #prefix>
              <svg-icon name="user" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            type="password"
            @keyup.enter="handleLogin"
            maxlength="20"
            placeholder="密码"
            show-password
          >
            <template #prefix>
              <svg-icon name="password" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <div class="input-box">
            <el-input
              v-model="form.code"
              maxlength="4"
              style="width: 305px; float: left"
              @keyup.enter="handleLogin"
            ></el-input>
            <el-image
              v-loading="captchaLoading"
              :src="captchaData.captchaImg"
              class="captchaImg"
              @click="getCaptcha"
              style="
                margin-left: 5px;
                width: 140px;
                height: 47px;
                border-radius: 3px;
              "
            ></el-image>
          </div>
        </el-form-item>
        <div style="margin-bottom: 15px">
          <el-checkbox v-model="form.isRememberValue">
            <div style="color: white">{{ $t("labels.remember") }}</div>
          </el-checkbox>
        </div>

        <el-form-item label="">
          <div class="button-container">
            <el-button type="primary" @click="handleLogin" :loading="loading">{{
              $t("buttons.login")
            }}</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script setup>
import { reactive, ref, onMounted } from "vue";
import http from "@/utils/request";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import qs from "qs";
import { ElMessage } from "element-plus";
import { encryptHandler, decryptHandler } from "@/utils/jsencrypt";
import Cookies from "js-cookie";
import { throttle } from "lodash";
import load from "@/utils/load.js"; // 引入

const loading = ref(false);
const store = useStore();
const router = useRouter();
const captchaData = ref({});
const code = ref("");
const captchaLoading = ref(false);
const form = ref({
  username: "",
  password: "",
  isRememberValue: false,
  code: "",
  uuid: "",
});

const rules = ref({
  username: [
    { required: true, message: "用户名不能为空", trigger: "blur" },
    { min: 3, max: 20, message: "用户名长度在3-20之间", trigger: "blur" },
  ],
  password: [{ required: true, message: "密码不能为空", trigger: "blur" }],
  code: [{ required: true, message: "验证码不能为空", trigger: "blur" }],
});
const getCookie = () => {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const isRememberValue = Cookies.get("isRememberValue");

  form.value = {
    username: username == undefined ? form.value.username : username,
    password:
      password == undefined ? form.value.password : decryptHandler(password),
    isRememberValue:
      isRememberValue == undefined ? false : Boolean(isRememberValue),
    code: "",
  };
};
onMounted(() => {
  getCookie();
  getCaptcha();
});

const formValidate = ref(null);
const handleLogin = async () => {
  loading.value = true;

  formValidate.value.validate(async (isValid, invalidFields) => {
    if (isValid) {
      load.show();
      if (form.value.isRememberValue) {
        //验证通过记住密码
        Cookies.set("username", form.value.username, { expires: 30 });
        Cookies.set("password", encryptHandler(form.value.password), {
          expires: 30,
        });
        Cookies.set("isRememberValue", form.value.isRememberValue, {
          expires: 30,
        });
      } else {
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("isRememberValue");
      }

      let result = await http.post(
        `/login?${qs.stringify(form.value)
        }`
      );
      let data = result.data;
      if (result.data.code == 200) {
        loading.value = false;
        const token = data.data.token;
        const menuList = data.data.menuList;
        const currentUser = data.data.currentUser;
        const authorityStr = data.data.authorityStr;

        ElMessage.success(data.msg);
        console.log("登录成功");
        store.commit("SET_TOKEN", token);
        store.commit("SET_MENU_LIST", menuList);
        store.commit("SET_CURRENT_USER", currentUser);
        sessionStorage.setItem("permission", authorityStr);
        router.push("/index");
        load.hide();
      } else {
        getCaptcha();
        loading.value = false;
        load.hide();
        document.querySelector("canvas")
          ? document.querySelector("canvas").remove()
          : "";
        document.getElementById("app").style = "";
      }
    } else {
      loading.value = false;
      load.hide();
    }
  });
};
const resetForm = () => {
  formValidate.value.resetFields();
};
const getCaptcha = async () => {
  form.value.code = "";
  captchaLoading.value = true;
  const captchaRes = await http.get(`/captcha`);
  if (captchaRes.data.code === 200) {
    captchaData.value = captchaRes.data.data;
    form.value.uuid = captchaRes.data.data.uuid;
    captchaLoading.value = false;
  } else {
    captchaLoading.value = false;
  }
};
</script>

<style lang="less" scoped>
/deep/ .el-checkbox__input.is-checked + .el-checkbox__label {
  color: black;
}
/deep/ .el-form-item__label {
  color: black;
}
/deep/ .el-checkbox {
  color: black;
}
.container {
  min-height: 100vh;
  width: 100%;
  background-color: #2d3a4b;
  overflow: hidden;
  display: flex;
  align-items: center;

  .login {
    width: 450px;
    margin: 150px auto;
    box-sizing: border-box;
    .login-text {
      font-size: 26px;
      color: #eee;
      margin: 0 auto 40px auto;
      text-align: center;
      font-weight: 700;
    }

    .input-box {
      height: 47px;
    }
    .button-container {
      width: 100%;

      text-align: center;
      button {
        width: 100%;
        height: 40px;
        font-size: 16px;
      }
    }
  }
}
</style>
<style lang="less">
#login-container {
  .el-loading-spinner {
    top: 50%;
    margin-top: calc((0px - 32px) / 2);
    width: 100%;
    text-align: center;
    position: absolute;
  }
  .el-loading-spinner .circular {
    display: inline;
    height: 30px;
    width: 30px;
    animation: loading-rotate 2s linear infinite;
  }
  .el-input__inner {
    height: 47px;
    background: transparent;
    color: white;
    font-size: 15px;
  }

  .el-input__wrapper {
    background: transparent;
  }
  .el-form-item {
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
  .el-input__wrapper {
    box-shadow: 0 0 0 1px hsla(0, 0%, 100%, 0.1) inset;
  }
}
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
  -webkit-transition: "color 9999s ease-out, background-color 9999s ease-out";

  -webkit-transition-delay: 9999s;
}
</style>